package cn.accjiyun.controller.sale;

import cn.accjiyun.common.controller.BaseController;
import cn.accjiyun.common.entity.PageModel;
import cn.accjiyun.common.entity.QueryEntity;
import cn.accjiyun.common.utils.WebUtils;
import cn.accjiyun.entity.sale.Customer;
import cn.accjiyun.service.sale.CustomerService;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jiyun on 2017/5/3.
 */
@Controller
@RequestMapping("/admin/sale")
public class AdminCustomerController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(AdminCustomerController.class);
    private static String addCustomerPage = getViewPath("/admin/sale/customer-add");
    private static String customerListPage = getViewPath("/admin/sale/customer-list");

    @Autowired
    private CustomerService customerService;

    @InitBinder({"customer"})
    public void initBinderSysUser(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("customer.");
    }

    /**
     * 创建客户
     *
     * @param customer 客户实体
     * @return Map<String,Object>
     */
    @RequestMapping("/createCustomer")
    @ResponseBody
    public String createCustomer(HttpServletRequest request,
                                 @ModelAttribute("customer") Customer customer) {
        JsonObject resultJson = new JsonObject();
        try {
            customerService.createCustomer(customer);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "添加成功");
            resultJson.addProperty("url", "/admin/sale/customerList");
        } catch (Exception e) {
            logger.error("AdminCustomer.createCustomer()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "添加失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/deleteCustomer")
    @ResponseBody
    public String deleteCustomer(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String[] customerIdsString = request.getParameter("customerId").split(",");
            int[] customerIds = new int[customerIdsString.length];
            for (int i = 0; i < customerIdsString.length; i++) {
                customerIds[i] = Integer.valueOf(customerIdsString[i]);
            }
            if (customerIdsString != null && customerIdsString.length > 0) {
                customerService.deleteCustomer(customerIds);
            }
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "删除成功");
            resultJson.addProperty("url", "reload");
        } catch (Exception e) {
            logger.error("AdminCustomerController.deleteCustomer()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "删除失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/getCustomerList")
    @ResponseBody
    public String getCustomerList(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            QueryEntity queryEntity = new QueryEntity();
            Map likeStrings = new HashMap();
            String keyword = request.getParameter("keyword");
            if (WebUtils.isValidateRealString(keyword)) {
                likeStrings.put("customerName", keyword);
                likeStrings.put("principalName", keyword);
            }
            queryEntity.setLikeStrings(likeStrings);
            PageModel<Customer> page = new PageModel();
            page.setPageSize(5);
            int pageNo = Integer.valueOf(request.getParameter("pageNo"));
            page.setPageNo(pageNo);
            List<Customer> customerList = customerService.queryCustomerPage(queryEntity, page);
            JsonArray array = new JsonArray();
            for (Customer customer : customerList) {
                JsonObject list = new JsonObject();
                list.addProperty("customerId", customer.getCustomerId());
                list.addProperty("customerName", customer.getCustomerName());
                list.addProperty("principalName", customer.getPrincipalName());
                list.addProperty("mobile", customer.getMobile());
                list.addProperty("address", customer.getAddress());
                list.addProperty("comments", customer.getComments());
                array.add(list);
            }
            resultJson.addProperty("status", 200);
            resultJson.addProperty("pages", page.getTotalPageSize());
            JsonObject list = new JsonObject();
            list.add("list", array);
            resultJson.add("data", list);
        } catch (Exception e) {
            logger.error("AdminCustomerController.getCustomerList()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "获取列表失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/updateCustomer")
    @ResponseBody
    public String updateCustomer(HttpServletRequest request, @ModelAttribute("customer") Customer customer) {
        JsonObject resultJson = new JsonObject();
        try {
            customerService.updateCustomer(customer);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("url", "reload");
            resultJson.addProperty("msg", "更新成功");
        } catch (Exception e) {
            logger.error("AdminCustomer.updateCustomer()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "更新失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/customerAdd")
    public ModelAndView initUserAddPage() {
        ModelAndView model = new ModelAndView();
        model.setViewName(addCustomerPage);
        return model;
    }

    @RequestMapping("/customerList")
    public ModelAndView initUserListPage() {
        ModelAndView model = new ModelAndView();
        model.setViewName(customerListPage);
        return model;
    }

}
